// 登陆路由
const express = require("express");
// 引入connect-multiparty中间件
var multipart = require("connect-multiparty");
// 创建中间件对象
var multipartMiddleware = multipart();
// 创建路由对象
const login = express.Router();
// // 引入mysql
// const mysql=require('mysql');
// 引入数据库配置
const db = require("../mysql");
// 引入jwt token工具
const JwtUtil = require("../jwt");
// 引入邮件
const nodemail = require("../nodemailer")

// 前台登陆验证
login.post("/userlogin", multipartMiddleware, (req, res) => {
  // console.log(req.body);
  const sqlStr = `select * from users where phone=${req.body.phone} and password=${req.body.password}`;
  db.query(sqlStr, (error, results) => {
    if (results[0]==undefined) {
      return res.json({ status: 404, message: '登陆失败' });
    } else {
      console.log(results[0]);
      // 登陆成功，添加token验证
      let id = results[0].id.toString();
      // 将用户id传入并生成token
      let jwt = new JwtUtil(id);
      let token = jwt.generateToken();
      // 将 token 返回给客户端
      return res.json({
        status: 200,
        message: "登陆成功",
        token: token,
        data: results[0],
      });

    }
  });
});

// 后台管理获取用户
login.get("/getAdmin", multipartMiddleware, (req, res) => {
  const sqlStr = "select * from admin";
  db.query(sqlStr, (err, results) => {
    if (err) return res.json({ status: 404, message: error });
    res.json({ status: 200, data: results });
  });
});

// 后台管理验证登陆
login.post("/login", multipartMiddleware, (req, res) => {
  console.log(req.body);
  const sqlStr = "select * from admin";
  db.query(sqlStr, (error, results) => {
    if (error) {
      return res.json({ status: 404, message: error });
    } else {
      const flag = results.some((item) => {
        return (
          item.username == req.body.username &&
          item.password == req.body.password
        );
      });
      if (flag) return res.json({ status: 200, message: "登陆成功" });
      else return res.json({ status: 404, message: "登陆失败" });
    }
  });
});

// 发送邮件
login.get("/email", multipartMiddleware, async (req, res) => {
  console.log(req.query)
  // 判断数据库是否存在该注册邮箱
  const sqlStr = `select * from users where email='${req.query.email}'`
  db.query(sqlStr,async (err, results) => {
    if (err) return res.json({ code: 400, message: error });
    if(results.length<1){
      return res.json({code:404,message:"不存在该邮箱"})
    }
    let mail = {
      // 发件人
      from: '2190368517@qq.com',
      // 主题
      subject: '校园二手书重置密码',//邮箱主题
      // 收件人
      to:req.query.email,//前台传过来的邮箱
      // 邮件内容，HTML格式
      text: '验证码:'+req.query.randomNum//发送验证码
    }
    await nodemail(mail)  //发送邮件
    res.json({ code: 200, data: results });
  });
});

module.exports = login
